import * as vscode from 'vscode';

export class ReGenerateImagePanel {

    public static readonly viewType = 'reGenerateImage';

    // ReGenerateImagePanel 的单例
    private static currentPanel: ReGenerateImagePanel | undefined;

    // 通过vscode创建的webviewPanel
    private readonly _panel: vscode.WebviewPanel;
    private _disposables: vscode.Disposable[] = [];

    private _extensionUri: vscode.Uri;

    private constructor(panel: vscode.WebviewPanel, extensionUri: vscode.Uri) {
		this._panel = panel;
		this._extensionUri = extensionUri;

		// Set the webview's initial html content
		this._update();

		// Listen for when the panel is disposed
		// This happens when the user closes the panel or when the panel is closed programmatically
		this._panel.onDidDispose(() => this.dispose(), null, this._disposables);

		// Update the content based on view changes
		this._panel.onDidChangeViewState(
			() => {
				if (this._panel.visible) {
					this._update();
				}
			},
			null,
			this._disposables
		);

		// Handle messages from the webview
		this._panel.webview.onDidReceiveMessage(
			message => {
				switch (message.command) {
					case 'alert':
						vscode.window.showErrorMessage(message.text);
						return;
					case 'selectFile':
						this._selectFile();
						return;
				}
			},
			null,
			this._disposables
		);
	}

    public dispose() {
		ReGenerateImagePanel.currentPanel = undefined;

		// Clean up our resources
		this._panel.dispose();

		while (this._disposables.length) {
			const x = this._disposables.pop();
			if (x) {
				x.dispose();
			}
		}
	}

    private _update() {
		const webview = this._panel.webview;
        this._updateForCat(webview, 'ReGenerate Image');
	}

    private _updateForCat(webview: vscode.Webview, catName: string) {
		this._panel.title = catName;
		this._panel.webview.html = this._getHtmlForWebview();
	}

    private _getHtmlForWebview() {
		const nonce = getNonce();

		return `<!DOCTYPE html>
			<html lang="en">
			<head>
				<meta charset="UTF-8">

				<!--
					Use a content security policy to only allow loading images from https or from our extension directory,
					and only allow scripts that have a specific nonce.
				-->
				<meta http-equiv="Content-Security-Policy" content="default-src 'none'; style-src ${this._panel.webview.cspSource} 'unsafe-inline'; script-src 'nonce-${nonce}';">

				<meta name="viewport" content="width=device-width, initial-scale=1.0">
				<title>ReGenerate Image</title>
				<style>
					body {
						padding: 20px;
						font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
					}
					.button {
						background-color: #0e639c;
						color: white;
						border: none;
						padding: 8px 12px;
						border-radius: 2px;
						cursor: pointer;
						margin-top: 10px;
						margin-right: 10px;
					}
					.button:hover {
						background-color: #1177bb;
					}
					.danger-button {
						background-color: #cc0000;
					}
					.danger-button:hover {
						background-color: #ff0000;
					}
					#file-display {
						margin-top: 20px;
						padding: 10px;
						border: 1px solid #ccc;
						border-radius: 2px;
						min-height: 30px;
						background-color: #f5f5f5;
					}
					ul {
						margin-top: 5px;
						padding-left: 20px;
					}
					li {
						margin-bottom: 5px;
						word-break: break-all;
					}
					.button-container {
						display: flex;
						flex-wrap: wrap;
					}
				</style>
			</head>
			<body>
                <h1>ReGenerate Image</h1>
				
				<div class="button-container">
					<button class="button" id="select-file-btn">添加文件</button>
					<button class="button danger-button" id="clear-files-btn">清空列表</button>
				</div>
				
				<div id="file-display">
					<p>尚未选择文件</p>
				</div>

				<script nonce="${nonce}">
					const vscode = acquireVsCodeApi();
					
					// 保存已选择的文件列表
					let selectedFiles = [];
					
					// 尝试从状态恢复
					const previousState = vscode.getState();
					if (previousState && previousState.files) {
						selectedFiles = previousState.files;
						updateFileDisplay();
					}
					
					document.getElementById('select-file-btn').addEventListener('click', () => {
						vscode.postMessage({
							command: 'selectFile'
						});
					});
					
					document.getElementById('clear-files-btn').addEventListener('click', () => {
						selectedFiles = [];
						updateFileDisplay();
						saveState();
					});

					// 监听来自扩展的消息
					window.addEventListener('message', event => {
						const message = event.data;
						
						if (message.command === 'fileSelected') {
							if (message.filePaths && message.filePaths.length > 0) {
								// 添加新选择的文件到列表中
								message.filePaths.forEach(path => {
									// 避免重复添加
									if (!selectedFiles.includes(path)) {
										selectedFiles.push(path);
									}
								});
								
								updateFileDisplay();
								saveState();
							}
						}
					});
					
					function updateFileDisplay() {
						const fileDisplay = document.getElementById('file-display');
						if (selectedFiles.length > 0) {
							let content = '<p>已选择以下文件:</p><ul>';
							selectedFiles.forEach(path => {
								content += '<li>' + path + '</li>';
							});
							content += '</ul>';
							fileDisplay.innerHTML = content;
						} else {
							fileDisplay.innerHTML = '<p>尚未选择文件</p>';
						}
					}
					
					function saveState() {
						vscode.setState({ files: selectedFiles });
					}
				</script>
			</body>
			</html>`;
	}

    public static createOrShow(extensionUri: vscode.Uri) {
		const column = vscode.window.activeTextEditor
			? vscode.window.activeTextEditor.viewColumn
			: undefined;

		// If we already have a panel, show it.
		if (ReGenerateImagePanel.currentPanel) {
			ReGenerateImagePanel.currentPanel._panel.reveal(column);
			return;
		}

		// Otherwise, create a new panel.
		const panel = vscode.window.createWebviewPanel(
			ReGenerateImagePanel.viewType,
			'ReGenerate Image',
			column || vscode.ViewColumn.One,
			ReGenerateImagePanel.getWebviewOptions(extensionUri),
		);

		ReGenerateImagePanel.currentPanel = new ReGenerateImagePanel(panel, extensionUri);
	}

    public static getWebviewOptions(extensionUri: vscode.Uri): vscode.WebviewOptions {
        return {
            // Enable javascript in the webview
            enableScripts: true,
    
            // And restrict the webview to only loading content from our extension's `media` directory.
            localResourceRoots: [vscode.Uri.joinPath(extensionUri, 'media')]
        };
    }

    // 打开文件选择对话框
    private async _selectFile() {
        const options: vscode.OpenDialogOptions = {
            canSelectMany: true, // 启用多选
            canSelectFiles: true, // 确保可以选择文件
            canSelectFolders: false, // 不允许选择文件夹
            openLabel: '选择文件',
            title: '请选择多个文件 (使用Ctrl或Command键进行多选)',
            filters: {
                '所有文件': ['*']
            }
        };

        // 显示提示
        vscode.window.showInformationMessage('请使用Ctrl(Windows)或Command(Mac)键点击多个文件进行选择');
        
        // 为了解决在Linux远程环境下对话框显示在主窗口后面的问题，
        // 先尝试激活VSCode窗口，然后再显示文件选择对话框
        await vscode.commands.executeCommand('workbench.action.focusActiveEditorGroup');
        
        const fileUris = await vscode.window.showOpenDialog(options);
        
        if (fileUris && fileUris.length > 0) {
            // 发送选择的文件路径到WebView
            this._panel.webview.postMessage({
                command: 'fileSelected',
                filePaths: fileUris.map(uri => uri.fsPath) // 发送所有选中的文件路径
            });
            
            // 显示选择的文件数量
            vscode.window.showInformationMessage(`已选择 ${fileUris.length} 个文件`);
        } else {
            // 用户取消了选择
            this._panel.webview.postMessage({
                command: 'fileSelected',
                filePaths: []
            });
        }
    }
}

// 生成随机nonce值的辅助函数
function getNonce() {
	let text = '';
	const possible = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
	for (let i = 0; i < 32; i++) {
		text += possible.charAt(Math.floor(Math.random() * possible.length));
	}
	return text;
}